package happens_before;

/**
 * @author juntao zhang
 */
public class FinalExample {

  private int i;                            //普通变量
  private final int j;                      //final变量
  private static FinalExample obj;

  public FinalExample() {     //构造函数
    i = 1;                        //写普通域
    j = 2;                        //写final域
    try {
      Thread.sleep(20);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("sleep end");
  }

  public static void writer() {    //写线程A执行
    System.out.println("writer");
    obj = new FinalExample();
    System.out.println("writer end");
  }

  public static void reader() {       //读线程B执行
    System.out.println("reader");
    FinalExample object = obj;       //读对象引用
    int a = object.i;                //读普通域
    int b = object.j;                //读final域
    System.out.println("reader end");
  }

  public static void main(String[] args) {
    new Thread(new Runnable() {
      @Override
      public void run() {
        FinalExample.writer();
      }
    }).start();
    new Thread(new Runnable() {
      @Override
      public void run() {
        FinalExample.reader();
      }
    }).start();
  }

}
